const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
const BlogModel = require('../models/blog')
const TagModel = require('../models/tag')

// 新建标签
router.post('/', async(ctx, next) => {
  ctx.body = {
    _id: (await TagModel.addTag(ctx.request.body.name))._id
  }
  return next()
})

// 根据id查找标签
router.get('/:id', async(ctx, next) => {
  const id = ctx.params.id
  if (!id.match(/^[0-9a-fA-F]{24}$/) || ctx.used) return next()
  ctx.body = await TagModel.getTagById(id, ctx.query.page)
  ctx.used = true
  return next()
})

// 根据开头查找标签
router.get('/:start', async(ctx, next) => {
  const start = ctx.params.start
  if (start.match(/^[0-9a-fA-F]{24}$/) || ctx.used) return next()
  ctx.body = await TagModel.findTagByStart(start)
  ctx.used = true
  return next()
})

// 获取全部标签
router.get('/', async(ctx, next) => {
  ctx.body = await TagModel.getAllTag()
  return next()
})

// 删除标签
router.delete('/:id', async(ctx, next) => {
  // 还没用到单独删除标签的接口
})

module.exports = router